package top.jfunc.token.redis;

import org.springframework.data.redis.core.RedisTemplate;
import top.jfunc.token.CaptchaManger;

import java.util.concurrent.TimeUnit;

/**
 * 基于redis的验证码管理器
 * @author xiongshiyan at 2018/10/8 , contact me with email yanshixiong@126.com or phone 15208384257
 */
public abstract class AbstractRedisCaptchaManager<M> implements CaptchaManger<M> {
    private RedisTemplate<Object,Object> redisTemplate;

    @Override
    public void updateCaptcha(M member, String captcha) {
        redisTemplate.opsForValue().set(key(member) , captcha , 1800, TimeUnit.SECONDS);
    }

    @Override
    public boolean verifyCaptcha(M member, String captcha) {
        String cap = (String) redisTemplate.opsForValue().get(key(member));
        return null != cap && cap.equalsIgnoreCase(captcha);
    }

    @Override
    public void deleteCaptcha(M member) {
        redisTemplate.delete(key(member));
    }


    /**
     * 根据实体或者标识获取key
     * @param m 实体或者标识
     * @return 返回保存标识和token关系的key
     */
    abstract protected String key(M m);

    public RedisTemplate<Object, Object> getRedisTemplate() {
        return redisTemplate;
    }

    public void setRedisTemplate(RedisTemplate<Object, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }
}
